<template>
  <div v-if="visible" class="modal-container" @click.self="closeModal">
    <div class="modal-overlay modal-main">
        <div class="modal-header">
          <h3 class="modal-title">数据插件管理</h3>
          <button class="modal-close" @click="closeModal">
            <svg class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M18 6L6 18M6 6l12 12" />
            </svg>
          </button>
        </div>
        <div class="modal-body">
          <div class="form-container">
            <TransitionGroup name="plugin-list" tag="div" class="plugin-list-container">
              <div v-for="plugin in sortedFormConfig" :key="plugin.id" class="plugin-section">
                <!-- Plugin Header with Move Buttons -->
                <div class="plugin-header">
                  <div class="plugin-info">
                    <h4>{{ plugin.name }}</h4>
                    <div class="plugin-switch">
                      <input
                        type="checkbox"
                        :id="'switch-' + plugin.id"
                        :checked="plugin.isEnable === 0"
                        @change="togglePluginEnable(plugin)"
                        class="switch-input"
                      />
                      <label :for="'switch-' + plugin.id" class="switch-label">
                      </label>
                    </div>
                    <p class="plugin-description">{{ plugin.description }}</p>
                    <p class="plugin-category">分类: {{ plugin.category }}</p>
                  </div>
                  <div class="plugin-actions">
                    <button
                      class="tech-btn move-btn"
                      @click="movePlugin(plugin.sort, 'up')"
                      :disabled="plugin.sort === 1">
                      ↑
                    </button>
                    <button
                      class="tech-btn move-btn"
                      @click="movePlugin(plugin.sort, 'down')"
                      :disabled="plugin.sort === formConfig.length">
                      ↓
                    </button>
                  </div>
                </div>

                <!-- Plugin Parameters -->
                <div v-if="plugin.params && plugin.params.length > 0">
                  <div v-for="param in plugin.params" :key="getParamKey(plugin.id, param)" class="form-item">
                    <div class="form-item-header">
                      <label :for="getParamKey(plugin.id, param)" class="form-label">
                        {{ param.label }}
                        <span v-if="param.required" class="required">*</span>
                      </label>
                    </div>

                    <!-- Input Field -->
                    <input
                      v-if="param.type === 'input'"
                      maxlength="50"
                      :id="getParamKey(plugin.id, param)"
                      v-model="formData[getParamKey(plugin.id, param)]"
                      :placeholder="param.placeholder"
                      class="form-input"
                      type="text"
                    >

                    <!-- Select Field -->
                    <select
                      v-if="param.type === 'select'"
                      :id="getParamKey(plugin.id, param)"
                      v-model="formData[getParamKey(plugin.id, param)]"
                      class="form-select"
                    >
                      <option value="" disabled>请选择</option>
                      <option
                        v-for="option in param.options"
                        :key="option.value"
                        :value="option.value"
                      >
                        {{ option.label }}
                      </option>
                    </select>

                    <!-- Textarea Field -->
                    <textarea
                      maxlength="100"
                      v-if="param.type === 'textarea'"
                      :id="getParamKey(plugin.id, param)"
                      v-model="formData[getParamKey(plugin.id, param)]"
                      :placeholder="param.placeholder"
                      class="form-textarea"
                      rows="4"
                    ></textarea>

                    <!-- Date Field -->
                    <input
                      v-if="param.type === 'date'"
                      :id="getParamKey(plugin.id, param)"
                      v-model="formData[getParamKey(plugin.id, param)]"
                      type="date"
                      class="form-input"
                      :placeholder="param.placeholder"
                    >

                    <!-- number Field -->
                    <input
                      v-if="param.type === 'number'"
                      :id="getParamKey(plugin.id, param)"
                      v-model="formData[getParamKey(plugin.id, param)]"
                      type="number"
                      class="form-input"
                    >

                    <!-- checkbox Field -->
                    <div>
                      <input
                        v-if="param.type === 'checkbox'"
                        :id="getParamKey(plugin.id, param)"
                        v-model="formData[getParamKey(plugin.id, param)]"
                        type="checkbox"> <span v-if="param.type === 'checkbox'" class="label-text">{{ param.label }}</span>
                    </div>

                    <!-- file Field -->
                    <FileUpload
                      v-if="param.type === 'file'"
                      v-model="formData[getParamKey(plugin.id, param)]"
                      :label="param.label"
                      :path="param.path"
                      :placeholder="param.placeholder"
                      :options="param.options"
                      :error="param.error"
                      :disabled="param.disabled"
                      :min="param.min"
                      :max="param.max"
                      :step="param.step"
                      :isInteger="param.isInteger"
                      :required="param.required"
                      :maxLength="param.maxLength"
                      :rows="param.rows"
                      :ref="(el: any) => setComponentRef('file_' + getParamKey(plugin.id, param), el)"
                    />

                    <!-- files Field -->
                    <FilesUpload
                      v-if="param.type === 'files'"
                      v-model="formData[getParamKey(plugin.id, param)]"
                      :label="param.label"
                      :path="param.path"
                      :placeholder="param.placeholder"
                      :options="param.options"
                      :error="param.error"
                      :disabled="param.disabled"
                      :min="param.min"
                      :max="param.max"
                      :step="param.step"
                      :isInteger="param.isInteger"
                      :required="param.required"
                      :maxLength="param.maxLength"
                      :rows="param.rows"
                      :ref="(el: any) => setComponentRef('files_' + getParamKey(plugin.id, param), el)"
                    />

                    <!-- rangePicker Field -->
                    <div v-if="param.type === 'rangePicker'" class="range-picker-container">
                      <div class="range-picker-item">
                        <label class="range-picker-label">开始日期时间</label>
                        <div class="datetime-input-group">
                          <input
                            :id="getParamKey(plugin.sort, param) + '_start_date'"
                            v-model="formData[getParamKey(plugin.id, param) + '_start_date']"
                            type="date"
                            class="form-input datetime-date-input"
                            :placeholder="'选择开始日期'"
                            @change="updateDateTimeValue(plugin.id, param, 'start')"
                          >
                          <TimeSelector
                            :id="getParamKey(plugin.id, param) + '_start_time'"
                            v-model="formData[getParamKey(plugin.id, param) + '_start_time']"
                            input-class="datetime-time-input"
                            placeholder="选择开始时间"
                            @change="updateDateTimeValue(plugin.id, param, 'start')"
                          />
                        </div>
                      </div>
                      <div class="range-picker-divider">至</div>
                      <div class="range-picker-item">
                        <label class="range-picker-label">结束日期时间</label>
                        <div class="datetime-input-group">
                          <input
                            :id="getParamKey(plugin.id, param) + '_end_date'"
                            v-model="formData[getParamKey(plugin.id, param) + '_end_date']"
                            type="date"
                            class="form-input datetime-date-input"
                            :placeholder="'选择结束日期'"
                            @change="updateDateTimeValue(plugin.id, param, 'end')"
                          >
                          <TimeSelector
                            :id="getParamKey(plugin.id, param) + '_end_time'"
                            v-model="formData[getParamKey(plugin.id, param) + '_end_time']"
                            input-class="datetime-time-input"
                            placeholder="选择结束时间"
                            @change="updateDateTimeValue(plugin.id, param, 'end')"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </TransitionGroup>
          </div>
        </div>
        <div class="modal-footer">
          <button class="tech-btn import-btn-cancel" @click="closeModal">取消</button>
          <button class="tech-btn import-btn-primary" style="margin-left: 10px" @click="handleConfirm">确定</button>
        </div>
    </div>
  </div>
  <!-- 全局loading遮罩层 -->
  <div v-if="isLoading" class="loading-overlay">
    <div class="spinner"></div>
  </div>
  <!-- 消息提示组件 -->
  <Message ref="messageRef" />
</template>

<script setup lang="ts">
import { ref, watch, reactive, onMounted, computed, nextTick } from 'vue'
import PluginAPI from './plugin.api.ts'
import FilesUpload from './FilesUpload.vue'
import FileUpload from './FileUpload.vue'
import TimeSelector from './TimeSelector.vue'
import Message from '../../components/BaseComponents/Message.vue';
import { useTimestampStore } from "@/stores/timestampStore.ts";
import fileImportApi from "@/views/fileImport/fileImport.api.ts";

interface PluginOption {
  label: string
  value: string
}

interface PluginParam {
  name: string
  type?: 'input' | 'select' | 'textarea' | 'date' | 'rangePicker' | 'number' | 'checkbox' | 'file' | 'files'
  field?: string
  label: string
  placeholder?: string
  value?: string | { startTime?: string; endTime?: string } | File[]
  required?: boolean
  options?: PluginOption[]
  min?: number
  max?: number
  path?: string
  error?: string
  disabled?: boolean
  step?: number
  isInteger?: boolean
  maxLength?: number
  rows?: number
}

interface Plugin {
  id: number
  name: string, // 插件名称
  type: string, // 插件类型
  version: string, // 插件版本
  executeCommand: string, // 执行命令
  executeFile: string, // 执行文件
  executeConfig: string, // 执行配置
  path: string, // 插件路径
  config: string,
  sort: number, // 排序
  isEnable: number, // 0 为启用 1 为停用
  inputPath: string, // 输入路径
  outputPath: string,
  params: PluginParam[],
  description?: string,
  category?: string
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['update:visible', 'confirm', 'success'])
const formRef = ref()
const formData = reactive<Record<string, any>>({})
// loding 控制
const isLoading = ref(false)
// 消息提示组件引用
const messageRef = ref<InstanceType<typeof Message> | null>(null);
// 组件引用映射
const componentRefMap = reactive<Record<string, any>>({})
// 根据number排序的计算属性
const sortedFormConfig = computed(() => {
  const sorted = [...formConfig.value].sort((a: Plugin, b: Plugin) => a.sort - b.sort)
  console.log('Sorted plugins:', sorted)
  return sorted
})

// 更新日期时间值的函数
const updateDateTimeValue = (pluginId: number, param: PluginParam, type: 'start' | 'end') => {
  const dateKey = getParamKey(pluginId, param) + `_${type}_date`
  const timeKey = getParamKey(pluginId, param) + `_${type}_time`
  
  const dateValue = formData[dateKey]
  const timeValue = formData[timeKey]
  
  // 构建组合的日期时间字符串，需要同时有日期和时间
  const combinedDateTime = (dateValue && timeValue) ? `${dateValue} ${timeValue}` : ''
  // 更新参数值（无论是否为空都要更新）
  formConfig.value.forEach(plugin => {
    if (plugin.id === pluginId) {
      plugin.params.forEach(p => {
        if (p.name === param.name && p.type === 'rangePicker') {
          if (!p.value || typeof p.value !== 'object' || Array.isArray(p.value)) {
            p.value = { startTime: '', endTime: '' }
          }
          if (type === 'start') {
            p.value.startTime = combinedDateTime
          } else {
            p.value.endTime = combinedDateTime
          }
        }
      })
    }
  })
}

// 监听formData的变化，更新formConfig中对应的value值
watch(formData, (newVal) => {
  formConfig.value.forEach(plugin => {
    plugin.params.forEach(param => {
      if (param.type === 'rangePicker') {
        // rangePicker的值更新已经在updateDateTimeValue函数中处理
        return
      } else {
        const key = getParamKey(plugin.id, param)
        if (key in newVal) {
          param.value = newVal[key]
        }
      }
    })
  })
}, { deep: true })

// 移动插件的方法
const movePlugin = (currentNumber: number, direction: 'up' | 'down') => {
  console.log('Moving plugin:', currentNumber, direction);
  const currentIndex = formConfig.value.findIndex(item => item.sort === currentNumber)
  const targetIndex = direction === 'up' ? currentIndex - 1 : currentIndex + 1

  if (targetIndex >= 0 && targetIndex < formConfig.value.length) {
    try {
      // 保存当前所有数据
      const tempData = { ...formData }
      const tempConfig = [...formConfig.value]

      // 移动插件
      const [movedPlugin] = tempConfig.splice(currentIndex, 1)
      tempConfig.splice(targetIndex, 0, movedPlugin)

      // 更新所有插件的 sort 值
      tempConfig.forEach((plugin, index) => {
        plugin.sort = index + 1
      })

      // 更新表单数据
      tempConfig.forEach((plugin) => {
        if (plugin.params) {
          plugin.params.forEach((param: PluginParam) => {
            const oldKey = getParamKey(plugin.id, param)
            const newKey = getParamKey(plugin.id, param)
            if (oldKey in tempData) {
              formData[newKey] = tempData[oldKey]
            }
          })
        }
      })

      // 更新配置
      formConfig.value = tempConfig

      // 触发更新
      nextTick(() => {
        console.log('Plugin moved successfully:', {
          from: currentIndex,
          to: targetIndex,
          newConfig: formConfig.value
        })
      })
    } catch (error) {
      console.error('Error moving plugin:', error)
    }
  }
}

// 添加移动动画样式
const pluginListTransition = {
  name: 'plugin-list',
  tag: 'div',
  class: 'plugin-list-container'
}

// 模拟后端返回的表单配置数据
const formConfig = ref<Plugin[]>([]);

const closeModal = () => {
  emit('update:visible', false)
  Object.keys(formData).forEach(key => {
    formData[key] = ''
  })
}

const handleConfirm = async () => {
  const isValid = validateForm()
  if (isValid) {
    await handleSubmit()
  }
}

// 保存插件配置函数
const handleSubmit = async () => {
  isLoading.value = true;
  
  try {
    // 更新所有插件的参数值
    formConfig.value.forEach(plugin => {
      plugin.params.forEach(param => {
        const key = getParamKey(plugin.id, param);
        if (param.type === 'rangePicker') {
          const startKey = key + '_start';
          const endKey = key + '_end';
          if (formData[startKey] && formData[endKey]) {
            param.value = {
              startTime: formatDateTime(formData[startKey]),
              endTime: formatDateTime(formData[endKey])
            };
          }
        } else if (param.type === 'file' || param.type === 'files') {
          // 文件类型的处理在组件中已完成
          param.value = formData[key] || [];
        } else {
          param.value = formData[key];
        }
      });
    });

    // 深拷贝配置数据避免引用问题
    let params = formConfig.value
    
    // 调用编辑插件API
    const res: any = await PluginAPI.editPlugins(params);
    
    if (res && res.code === 200) {
      // 触发成功事件
      emit('confirm', res.data);
      
      // 关闭模态框
      closeModal();
    } else {
      messageRef.value?.show({
        type: 'error',
        content: res?.msg || '插件配置保存失败',
        duration: 3000
      });
    }
  } catch (error: any) {
    messageRef.value?.show({
      type: 'error',
      content: error.response.data.msg,
      duration: 3000
    });
  } finally {
    isLoading.value = false;
  }
}

// 生成参数的唯一标识符
const getParamKey = (pluginNumber: number, param: PluginParam): string => {
  return `plugin_${pluginNumber}_${param.name}`
}

// 表单验证
const validateForm = () => {
  let isValid = true
  // 验证所有插件的必填参数
  formConfig.value.forEach(plugin => {
    plugin.params.forEach(param => {
      if (param.type === 'rangePicker') {
        const startDateKey = getParamKey(plugin.id, param) + '_start_date'
        const startTimeKey = getParamKey(plugin.id, param) + '_start_time'
        const endDateKey = getParamKey(plugin.id, param) + '_end_date'
        const endTimeKey = getParamKey(plugin.id, param) + '_end_time'
        
        const startDate = formData[startDateKey]
        const startTime = formData[startTimeKey]
        const endDate = formData[endDateKey]
        const endTime = formData[endTimeKey]
        
        // 检查日期时间的完整性
        const hasStartDate = !!startDate
        const hasEndDate = !!endDate
        const hasStartTime = startTime
        const hasEndTime = endTime
        
        // 如果只有开始日期或只有结束日期，提醒补全
        if (hasStartDate && !hasEndDate) {
          isValid = false
          messageRef.value?.show({
            type: 'warning',
            content: `插件"${plugin.name}"中的"${param.label}"请同时选择开始和结束日期`,
            duration: 3000
          });
          return;
        }
        
        if (!hasStartDate && hasEndDate) {
          isValid = false
          messageRef.value?.show({
            type: 'warning',
            content: `插件"${plugin.name}"中的"${param.label}"请同时选择开始和结束日期`,
            duration: 3000
          });
          return;
        }
        
        // 如果有时间但没有对应的日期，提醒补全日期
        if (hasStartTime && !hasStartDate) {
          isValid = false
          messageRef.value?.show({
            type: 'warning',
            content: `插件"${plugin.name}"中的"${param.label}"请先选择开始日期`,
            duration: 3000
          });
          return;
        }
        
        if (hasEndTime && !hasEndDate) {
          isValid = false
          messageRef.value?.show({
            type: 'warning',
            content: `插件"${plugin.name}"中的"${param.label}"请先选择结束日期`,
            duration: 3000
          });
          return;
        }
        
        // 如果有日期但没有对应的时间，提醒补全时间
        if (hasStartDate && !hasStartTime) {
          isValid = false
          messageRef.value?.show({
            type: 'warning',
            content: `插件"${plugin.name}"中的"${param.label}"请选择开始时间`,
            duration: 3000
          });
          return;
        }
        
        if (hasEndDate && !hasEndTime) {
          isValid = false
          messageRef.value?.show({
            type: 'warning',
            content: `插件"${plugin.name}"中的"${param.label}"请选择结束时间`,
            duration: 3000
          });
          return;
        }
        
        // 验证开始时间不能晚于结束时间（只有在都有完整的日期时间时才比较）
        if (hasStartDate && hasEndDate && hasStartTime && hasEndTime) {
          const startDateTime = new Date(`${startDate} ${startTime}`)
          const endDateTime = new Date(`${endDate} ${endTime}`)
          
          if (isNaN(startDateTime.getTime()) || isNaN(endDateTime.getTime())) {
            isValid = false
            messageRef.value?.show({
              type: 'warning',
              content: '日期时间格式不正确',
              duration: 3000
            });
            return;
          } else if (startDateTime >= endDateTime) {
            isValid = false
            messageRef.value?.show({
              type: 'warning',
              content: '开始时间不能晚于或等于结束时间',
              duration: 3000
            });
            return;
          }
        }
        
        // 检查rangePicker必填参数
        if (param.required) {
          if (!hasStartDate || !hasEndDate) {
            isValid = false
            messageRef.value?.show({
              type: 'warning',
              content: `插件"${plugin.name}"中的"${param.label}"为必填项`,
              duration: 3000
            });
            return;
          }
        }
      }
      // 检查其他必填参数
      if (param.required && param.type !== 'rangePicker') {
        const value = formData[getParamKey(plugin.id, param)];
        if (!value || (Array.isArray(value) && value.length === 0)) {
          isValid = false
          messageRef.value?.show({
            type: 'warning',
            content: `插件"${plugin.name}"中的"${param.label}"为必填项`,
            duration: 3000
          });
          return;
        }
      }
    })
  })
  return isValid
}

// 将时间字符串转换为datetime-local格式
const toDateTimeLocalFormat = (dateTimeString: string): string => {
  if (!dateTimeString) return ''
  
  // 处理 "YYYY-MM-DD HH:mm:ss" 格式，直接转换为datetime-local格式
  if (dateTimeString.includes(' ') && !dateTimeString.includes('T')) {
    // 直接将空格替换为T，不进行时区转换
    return dateTimeString.replace(' ', 'T')
  }
  
  // 处理其他格式，尝试解析但保持本地时间
  try {
    const date = new Date(dateTimeString)
    if (!isNaN(date.getTime())) {
      // 获取本地时间的年月日时分秒，避免UTC转换
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      
      return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`
    }
  } catch (error) {
    console.warn('解析时间字符串失败:', dateTimeString, error)
  }
  
  return ''
}

// 格式化日期为 "YYYY-MM-DD HH:mm:ss" 格式
const formatDateTime = (dateTimeString: string): string => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  if (isNaN(date.getTime())) return ''
  
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 分离日期时间字符串为日期和时间部分
const splitDateTime = (dateTimeString: string): { date: string; time: string } => {
  if (!dateTimeString) return { date: '', time: '' }
  
  // 处理 "YYYY-MM-DD HH:mm:ss" 格式
  if (dateTimeString.includes(' ')) {
    const [datePart, timePart] = dateTimeString.split(' ')
    return { date: datePart, time: timePart }
  }
  
  // 处理 "YYYY-MM-DDTHH:mm:ss" 格式
  if (dateTimeString.includes('T')) {
    const [datePart, timePart] = dateTimeString.split('T')
    return { date: datePart, time: timePart }
  }
  
  // 只有日期部分
  return { date: dateTimeString, time: '' }
}

// 初始化表单数据，回显带有value属性的字段值
const initFormData = () => {
  formConfig.value.forEach(plugin => {
    plugin.params.forEach(param => {
      if ('value' in param && param.value !== undefined && param.value !== null) {
        if (param.type === 'rangePicker' && param.value && typeof param.value === 'object' && !Array.isArray(param.value)) {
          // 处理日期范围选择器的初始化 - 使用分离的日期时间输入
          const startDateKey = getParamKey(plugin.id, param) + '_start_date'
          const startTimeKey = getParamKey(plugin.id, param) + '_start_time'
          const endDateKey = getParamKey(plugin.id, param) + '_end_date'
          const endTimeKey = getParamKey(plugin.id, param) + '_end_time'
          
          // 如果有startTime，分离为日期和时间
          if ('startTime' in param.value && param.value.startTime) {
            const { date, time } = splitDateTime(param.value.startTime)
            formData[startDateKey] = date
            formData[startTimeKey] = time
          } else {
            formData[startDateKey] = ''
            formData[startTimeKey] = ''
          }
          
          // 如果有endTime，分离为日期和时间
          if ('endTime' in param.value && param.value.endTime) {
            const { date, time } = splitDateTime(param.value.endTime)
            formData[endDateKey] = date
            formData[endTimeKey] = time
          } else {
            formData[endDateKey] = ''
            formData[endTimeKey] = ''
          }
        } else {
          // 确保文件类型参数有默认的空数组值
          if ((param.type === 'file' || param.type === 'files')) {
            formData[getParamKey(plugin.id, param)] = Array.isArray(param.value) ? param.value : []
          } else {
            formData[getParamKey(plugin.id, param)] = param.value
          }
        }
      } else {
        // 为没有初始值的参数设置默认值
        if (param.type === 'file' || param.type === 'files') {
          formData[getParamKey(plugin.id, param)] = []
        } else if (param.type === 'rangePicker') {
          const startDateKey = getParamKey(plugin.id, param) + '_start_date'
          const startTimeKey = getParamKey(plugin.id, param) + '_start_time'
          const endDateKey = getParamKey(plugin.id, param) + '_end_date'
          const endTimeKey = getParamKey(plugin.id, param) + '_end_time'
          formData[startDateKey] = ''
          formData[startTimeKey] = ''
          formData[endDateKey] = ''
          formData[endTimeKey] = ''
        } else {
          formData[getParamKey(plugin.id, param)] = ''
        }
      }
    })
  })
}
function getPluginFun() {
  let params = {
    type: 1
  }
  PluginAPI.getPlugins(params).then((res:any) => {
    if (res && res.code == 200) {
      try {
        // 处理params为null的情况，设置默认空数组
        const processedData = res.data.map((plugin: Plugin) => ({
          ...plugin,
          params: (plugin.params || []).map((param: PluginParam) => {
            // 处理rangePicker类型的JSON字符串值
            if (param.type === 'rangePicker' && typeof param.value === 'string') {
              try {
                param.value = JSON.parse(param.value);
              } catch (error) {
                console.warn('解析rangePicker值失败:', param.value, error);
                param.value = { startTime: '', endTime: '' };
              }
            }
            return param;
          }),
          description: plugin.description || '',
          category: plugin.category || '',
          sort: plugin.sort || 0
        }));

        // 确保数据按sort排序
        processedData.sort((a: Plugin, b: Plugin) => a.sort - b.sort)

        formConfig.value = processedData
        console.log('Loaded and processed plugins:', formConfig.value)
        // 初始化表单数据
        initFormData()
      } catch (error) {
        console.error('Error processing plugin data:', error)
        emit('success', {
          type: 'error',
          content: '处理插件数据失败',
          duration: 500
        })
      }
    } else {
      emit('success', {
        type: 'error',
        content: '获取插件失败',
        duration: 500
      })
    }
  }).catch(error => {
    console.error('Error fetching plugins:', error)
    emit('success', {
      type: 'error',
      content: error.response.data.msg,
      duration: 500
    })
  })
}
const pluginModelRef = ref<HTMLElement | null>(null)
// 在组件挂载时初始化数据
onMounted(() => {
  getPluginFun();
})

watch(() => props.visible, (newVal) => {
  if (newVal) {
    document.body.style.overflow = 'hidden'
  } else {
    document.body.style.overflow = ''
  }
})

// 添加 watch 来监控数据变化
watch(formConfig, (newVal) => {
  console.log('Form config changed:', newVal)
}, { deep: true })

// 设置组件引用
const setComponentRef = (key: string, el: any) => {
  if (el) {
    componentRefMap[key] = el
  }
}

const togglePluginEnable = (plugin: Plugin) => {
  // 切换插件启用状态：0表示启用，1表示停用
  plugin.isEnable = plugin.isEnable === 0 ? 1 : 0
}
</script>

<style scoped>
.form-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 10px;
}

.form-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.move-btn {
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  margin: 0 2px;
}

.form-label {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-color);
}

.required {
  color: var(--error-color);
  margin-left: 4px;
}

.form-input,
.form-select,
.form-textarea {
  padding: 8px 12px;
  border: 1px solid var(--input-border-color);
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.2s;
  width: 100%;
  background: var(--input-background);
  color: var(--text-color);
}

/* Date input specific styles */
input[type="date"].form-input {
  font-family: inherit;
  cursor: pointer;
}

input[type="date"].form-input::-webkit-calendar-picker-indicator {
  cursor: pointer;
  padding: 4px;
  margin-right: 2px;
  opacity: 0.6;
  transition: opacity 0.2s;
}

input[type="date"].form-input::-webkit-calendar-picker-indicator:hover {
  opacity: 1;
}

/* DateTime-local input specific styles */
input[type="datetime-local"].form-input {
  font-family: inherit;
  cursor: pointer;
  min-width: 200px;
  pointer-events: auto;
}

input[type="datetime-local"].form-input::-webkit-calendar-picker-indicator {
  cursor: pointer;
  padding: 4px;
  margin-right: 2px;
  opacity: 0.6;
  transition: opacity 0.2s;
}

input[type="datetime-local"].form-input::-webkit-calendar-picker-indicator:hover {
  opacity: 1;
}

.form-textarea {
  resize: vertical;
  min-height: 100px;
}

.modal-container {
  position: fixed;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 50;
  background-color: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(4px);
}

.modal-overlay {
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 1000px;
  max-height: 90vh;
  overflow: hidden;
  position: relative;
  /* border: 1px solid rgba(30, 64, 175, 0.1); */
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 30px;
  flex-shrink: 0;
}


.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-color);
}

.dark-mode .modal-title {
  color: var(--text-color);
}

.modal-close {
  background: transparent;
  border: none;
  cursor: pointer;
  color: var(--text-color);
  padding: 4px;
  border-radius: 4px;
}

.modal-close:hover {
  color: var(--global-color-black);
}

.modal-body {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
  scroll-behavior: smooth;
}



.modal-body::-webkit-scrollbar {
  width: 8px;
}

.modal-body::-webkit-scrollbar-track {
  background: var(--webkit-track-color);
  border-radius: 4px;
}

.modal-body::-webkit-scrollbar-thumb {
  background: var(--webkit-thumb-color);
  border-radius: 4px;
}

.modal-body::-webkit-scrollbar-thumb:hover {
  background: var(--webkit-thumb-hover-color);
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  padding: 16px 20px;

  flex-shrink: 0;
}

.import-btn-cancel, .import-btn-primary {
  height: 36px;
  font-size: 0.875rem;
  padding: 0.35rem 0.75rem;
  border-radius: 0.375rem;
  cursor: pointer;
  transition: all 0.2s ease;
}
.import-btn-cancel{
  color: var(--error-color) !important;
  border: 1px solid var(--error-color) !important;
}
.import-btn-cancel:hover {
 color: var(--text-color) !important;
  background: var(--error-color) !important;
}

.plugin-section {
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
  transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1),
              box-shadow 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
  //border: none;
  background-color: var(--se-sub-plate-bg-color);
}

.dark-mode .plugin-section {
  border: none;
  background-color: var(--se-sub-plate-bg-color);
}

.plugin-section:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.dark-mode .plugin-section:hover {
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
}

.plugin-info h4 {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
  margin: 0 0 8px 0;
}

.plugin-description {
  color: #4b5563;
  margin: 0 0 8px 0;
  font-size: 14px;
}

.plugin-category {
  color: var(--text-color);
  margin: 0;
  font-size: 13px;
}

.plugin-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.plugin-actions {
  display: flex;
  gap: 4px;
  margin-right: 5px;
}

/* 添加列表容器样式 */
.plugin-list-container {
  position: relative;
  width: 100%;
}

/* 添加移动动画 */
.plugin-list-move {
  transition: transform 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.plugin-list-enter-active,
.plugin-list-leave-active {
  transition: all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.plugin-list-enter-from,
.plugin-list-leave-to {
  opacity: 0;
  transform: translateY(30px);
}

.plugin-title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.plugin-switch {
  display: flex;
  align-items: center;
  margin: 8px 0;
}

.switch-input {
  display: none;
}

.switch-label {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 28px;
  background-color: #e5e7eb;
  border-radius: 14px;
  cursor: pointer;
  transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.switch-label::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(145deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0));
  opacity: 0;
  transition: opacity 0.3s ease;
}

.switch-label::after {
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: linear-gradient(145deg, #ffffff, #f3f4f6);
  top: 4px;
  left: 4px;
  transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
  box-shadow: 
    0 2px 4px rgba(0, 0, 0, 0.1),
    inset 0 -1px 2px rgba(0, 0, 0, 0.05),
    inset 0 1px 2px rgba(255, 255, 255, 0.8);
  will-change: transform;
}

.switch-input:checked + .switch-label {
  background: linear-gradient(145deg, #3b82f6, #2563eb);
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.2);
}

.switch-input:checked + .switch-label::before {
  opacity: 1;
}

.switch-input:checked + .switch-label::after {
  transform: translateX(32px);
  background: linear-gradient(145deg, #ffffff, #f8fafc);
  box-shadow: 
    0 2px 4px rgba(0, 0, 0, 0.1),
    inset 0 -1px 2px rgba(0, 0, 0, 0.05),
    inset 0 1px 2px rgba(255, 255, 255, 0.8);
}

/* 添加悬停效果 */
.switch-label:hover::after {
  transform: scale(1.1);
  box-shadow: 
    0 3px 6px rgba(0, 0, 0, 0.15),
    inset 0 -1px 2px rgba(0, 0, 0, 0.05),
    inset 0 1px 2px rgba(255, 255, 255, 0.9);
}

.switch-input:checked + .switch-label:hover::after {
  transform: translateX(32px) scale(1.1);
}

/* 添加点击效果 */
.switch-label:active::after {
  transform: scale(0.9);
  box-shadow: 
    0 1px 2px rgba(0, 0, 0, 0.1),
    inset 0 -1px 2px rgba(0, 0, 0, 0.05),
    inset 0 1px 2px rgba(255, 255, 255, 0.8);
  transition: all 0.2s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.switch-input:checked + .switch-label:active::after {
  transform: translateX(32px) scale(0.9);
}

/* 添加波纹效果 */
@keyframes ripple {
  0% {
    transform: scale(0);
    opacity: 0.5;
  }
  100% {
    transform: scale(2);
    opacity: 0;
  }
}

.switch-label::before {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.3) 0%, transparent 70%);
  transform: scale(0);
  opacity: 0;
  transition: transform 0.4s ease-out, opacity 0.4s ease-out;
}

.switch-input:checked + .switch-label::before {
  animation: ripple 0.6s ease-out;
}

/* Range Picker Styles */
.range-picker-container {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
  flex-wrap: wrap;
}

.range-picker-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
  min-width: 200px;
}

.range-picker-label {
  font-size: 12px;
  font-weight: 500;
  color: #6b7280;
  margin-bottom: 2px;
}

.range-picker-input {
  flex: 1;
  min-width: 180px;
}

.range-picker-divider {
  color: #6b7280;
  font-weight: 500;
  margin: 0 4px;
  margin-top: 16px;
  flex-shrink: 0;
}

/* DateTime Input Group Styles */
.datetime-input-group {
  display: flex;
  gap: 8px;
  width: 100%;
}

.datetime-date-input {
  flex: 1;
  min-width: 220px;
}

.datetime-time-input {
  flex: 1;
  min-width: 100px;
}

/* Responsive design for range picker */
@media (max-width: 640px) {
  .range-picker-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .range-picker-divider {
    text-align: center;
    margin: 8px 0;
  }
  
  .range-picker-item {
    min-width: unset;
  }
  
  .datetime-input-group {
    flex-direction: column;
    gap: 4px;
  }
  
  .datetime-date-input,
  .datetime-time-input {
    min-width: unset;
    width: 100%;
  }
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: var(--loading-bg-color);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.spinner {
  border: 8px solid #f3f3f3;
  border-top: 8px solid #3498db;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}


</style>
